#! /usr/bin/python
import pygtk
pygtk.require("2.0")
import gtk
import egg.trayicon
import os
import subprocess

VERSION = "2.5"
AUTHORS = ["James Willcox <snorp@snorp.net>"]
WEBSITE = "http://www.snorp.net/log/tangerine"
APPNAME = "Tangerine"
COMMENTS = "Tangerine is an application that allows you to publish music over the local network, using DAAP"
COPYRIGHT = "James Willcox <snorp@snorpt.net>"

install_dir = "@@INSTALLDIR@@"

UI = """
<ui>
    <popup name="Popup">
        <menuitem action='Preferences'/>
        <menuitem action='About'/>
        <menuitem action="Quit"/>
    </popup>
</ui>
"""

uimanager = gtk.UIManager()
sp = ''
prefs_proc = ''

def launch_tangerine():
    global sp
    texe = os.path.join(install_dir, 'app/tangerine-daemon.exe')
    sp = subprocess.Popen('mono ' + texe, shell=True)

def kill_tangerine():
    if sp.pid != '':
        os.kill(sp.pid, 2)

def show_about(event):
    about = gtk.AboutDialog()
    about.set_version(VERSION)
    about.set_website(WEBSITE)
    about.set_authors(AUTHORS)
    about.set_name(APPNAME)
    about.set_logo(
                    gtk.gdk.pixbuf_new_from_file_at_size(
                                    os.path.join(install_dir,"pixmaps/tangerine.svg"),
                                    24,24)
                    )
    about.set_comments(COMMENTS)
    about.set_copyright(COPYRIGHT)
    about.show_all() 
    
def show_preferences(event):
    global prefs_proc
    texe = os.path.join(install_dir, 'app/tangerine-properties.exe')
    prefs_proc = subprocess.Popen('mono ' + texe, shell=True)

def button_pressed(button, event):
    if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
        popup = uimanager.get_widget('/Popup')
        popup.popup(None, None, None, event.button, event.time)
        
def quit(event):
    kill_tangerine()
    gtk.main_quit()


def main():
    os.chdir('../')
    os.environ["LD_LIBRARY_PATH"] = "$LD_LIBRARY_PATH:%s" % install_dir + "/app"
    t = egg.trayicon.TrayIcon("Tangerine")
    ebox = gtk.EventBox()
    ebox.connect("button-press-event", button_pressed)
    t.add(ebox)
    
    ag = gtk.ActionGroup("TangerineActions")
    ag.add_actions([
                    ('Preferences', gtk.STOCK_PREFERENCES, '_Preferences', None, 'Show preferences', show_preferences),
                    ('Quit', gtk.STOCK_QUIT, '_Quit', None, 'Stop sharing', quit),
                    ('About', gtk.STOCK_ABOUT, '_About', None, 'About Tangerine', show_about)
                    ])
    uimanager.insert_action_group(ag, 0)
    uimanager.add_ui_from_string(UI)

    img = gtk.Image()
    pix = gtk.gdk.pixbuf_new_from_file_at_size(
                        os.path.join(install_dir,"pixmaps/tangerine.svg"),
                        24,24)
    img.set_from_pixbuf(pix)
    ebox.add(img)

    t.show_all()
    launch_tangerine()
    gtk.main()

main()
